package com.vancouver.knows;

import android.content.Context;
import android.location.Location;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

/**
 * 定位控制器
 * Created by chenxunlin01 on 2016/5/9.
 */
public class LocationController implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {

    private GoogleApiClient mGoogleApiClient;
    private Context context;
    private MainApplication imContext;
    private boolean isUpdateLocation;

    public LocationController(Context context ,boolean isUpdateLocation) {
        this.isUpdateLocation = isUpdateLocation;
        init(context);
    }

    private void init(Context context){
        this.context = context;
        imContext = (MainApplication) context.getApplicationContext();
    }

    public void onCreate(){
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(context).addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
        }
    }

    public void onStart(){
        if(mGoogleApiClient!=null){
            mGoogleApiClient.connect();
        }
    }

    public void onStop(){
        if(mGoogleApiClient!=null){
            mGoogleApiClient.disconnect();
        }
    }


    @Override
    public void onConnected(Bundle bundle) {
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            imContext.latitude = mLastLocation.getLatitude();
            imContext.longitude = mLastLocation.getLongitude();
        }

        if(isUpdateLocation){
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, createLocationRequest(), new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    if (location != null) {
                        imContext.latitude = location.getLatitude();
                        imContext.longitude = location.getLongitude();
                    }
                }
            });
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    private LocationRequest createLocationRequest() {
        LocationRequest myLocationRequest = new LocationRequest();
        myLocationRequest.setInterval(10000);//读取位置的时间间隔
        myLocationRequest.setFastestInterval(5000);//读取位置的最低时间间隔
        myLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        return myLocationRequest;
    }
}
